<template>
  <div ref="container" class="chart">
    <div ref="chartContainer" class="chartContainer"></div>
    <iframe ref="sizeWatch" class="size-watch"></iframe>
  </div>
</template>

<script>
import echarts from '@/libs/echarts'

export default {
  name: 'SimpleChart',
  props: {
    // eslint-disable-next-line vue/require-default-prop
    option: Object,
    height: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      myChart: null
    }
  },
  watch: {
    option: {
      handler(newName, oldName) {
        this.myChart.setOption(newName, true)
      },
      deep: true
    }
  },
  mounted() {
    // 全部引入
    // const echarts = require('echarts')

    this.myChart = echarts.init(this.$refs.chartContainer, 'macarons')
    this.$props.option && this.myChart.setOption(this.$props.option, true)
    this.resizeChart()
    // 使用 iframe 的 onresize 事件来监听 div 的 resize
    this.$refs.sizeWatch.contentWindow.onresize = this.$lodash.debounce(this.resizeChart, 300)
  },
  beforeDestroy() {
    this.myChart.dispose()
  },
  methods: {
    resizeChart() {
      let height = 0
      if (this.height === 0 && typeof (this.$refs.sizeWatch) !== 'undefined') {
        height = this.$refs.sizeWatch.contentWindow.innerHeight - 50
      } else {
        height = this.height
      }
      this.myChart.resize({ height: height })
    }
  }
}
</script>

<style scoped>
.chart {
  height: 100%;
  width: 100%;
}

.chartContainer {
  position: inherit !important;
}

.size-watch {
  width: 100%;
  height: 100%;
  top: 0;
  left: 0;
  position: absolute;
  visibility: hidden;
  margin: 0;
  padding: 0;
  border: 0;

}
</style>
